package com.cn.yugan.Activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.cn.yugan.Engine.Http.AddReqCookie;
import com.cn.yugan.Engine.Http.HtmlHandler;
import com.cn.yugan.Engine.Http.LoadUserface;
import com.cn.yugan.Widget.Webview.JSInterface;
import com.cn.yugan.Engine.Json.ArticleJson;
import com.cn.yugan.mobile.R;
import com.cn.yugan.Utils.StringConv;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;


import java.io.UnsupportedEncodingException;

/**
 * Created by Rover on 2016/8/3 .
 * Email 357319517@qq.com
 */
@SuppressLint("SetJavaScriptEnabled")
public class ArticleInfoActivity extends AppCompatActivity {
    private String aid;
    private String title;
    private TextView tv_title;
    private TextView tv_subtime;
    private TextView tv_username;
    private ImageView userimg;
    private Button bt_markup;
    private WebView wv_articleinfo;
    private TextView tv_markarticle;
    private TextView tv_comment;
    private TextView tv_agree;
    private String info = "";

    private ArticleJson aj;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_articleinfo);
        Intent intent = getIntent();
        aid = intent.getStringExtra("aid");
        init();
        
        initactionbar();
    
        initViews();
    }

    private void initactionbar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("yg" + aid);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    private void initViews() {
        tv_title = (TextView) findViewById(R.id.articleinfo_title_tv);
        tv_subtime = (TextView) findViewById(R.id.frag_subtime);
        tv_username = (TextView) findViewById(R.id.frag_username);
        wv_articleinfo = (WebView) findViewById(R.id.articleinfo_info_wv);
        //屏蔽webview长按事件
        wv_articleinfo.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        //点击事件
        tv_markarticle = (TextView) findViewById(R.id.articleinfo_mark_tv);
        tv_comment = (TextView) findViewById(R.id.articleinfo_comment_tv);
        tv_agree = (TextView) findViewById(R.id.articleinfo_agree_tv);
        userimg = (ImageView) findViewById(R.id.frag_cover_user_photo);
        bt_markup = (Button) findViewById(R.id.frag_markup);

        tv_markarticle.setOnClickListener(new onclicklistener());
        tv_comment.setOnClickListener(new onclicklistener());
        tv_agree.setOnClickListener(new onclicklistener());
        userimg.setOnClickListener(new onclicklistener());
        bt_markup.setOnClickListener(new onclicklistener());
        wv_articleinfo.setOnClickListener(new onclicklistener());
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (wv_articleinfo != null) {
            wv_articleinfo.destroy();
        }
    }


    private void init() {
        String url = getString(R.string.serverurl) + getString(R.string.article);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient(true,80,443);
        asyncHttpClient.addHeader("Cookie", AddReqCookie.getNormalheader(ArticleInfoActivity.this));
        RequestParams params = new RequestParams();
        params.put("aid", aid);
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    aj = new ArticleJson(StringConv.Unicode2UTF8(new String(bytes, "UTF-8")));
                    runOnUiThread(new Runnable() {
                        @SuppressLint("SetJavaScriptEnabled")
                        @Override
                        public void run() {
                            tv_username.setText(aj.getauthor());
                            String url = getString(R.string.imgserverurl) + aj.getuserface() + "imageView2/1/w/75/h/75:";
                            LoadUserface.getUserface(ArticleInfoActivity.this,url,new ImageView[]{userimg},null);
                            tv_title.setText(aj.gettitle());
                            tv_subtime.setText(aj.gettime() + "投稿");
                            info = aj.getcontent();
                            //webview
//                            DisplayMetrics displayMetrics = new DisplayMetrics();
//                            getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                            
                            wv_articleinfo.setWebChromeClient(new WebChromeClient(){
                                @Override
                                public void onProgressChanged(WebView view, int newProgress) {
                                    view.getSettings().setJavaScriptEnabled(true);
                                    super.onProgressChanged(view, newProgress);
                                    if (newProgress==100){
                                        addImageClickListner();
                                    }
                                }
                            });
                            wv_articleinfo.getSettings().setJavaScriptEnabled(true);
                            wv_articleinfo.loadDataWithBaseURL(null, HtmlHandler.ArticleinfoHandler(info), "text/html", "utf-8", null);
                            wv_articleinfo.addJavascriptInterface(new JSInterface(ArticleInfoActivity.this),"imggetter");
                            wv_articleinfo.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
                            
                        }
                    });
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                break;
        }
        return true;
    }

    private class onclicklistener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.articleinfo_mark_tv:
                    //收藏文章逻辑
                    break;
                case R.id.articleinfo_comment_tv:
                    Intent intent = new Intent(ArticleInfoActivity.this, CommentActivity.class);
                    intent.putExtra("aid",aid);
                    startActivity(intent);
                    break;
                case R.id.articleinfo_agree_tv:
                    //点赞逻辑
                    break;
                case R.id.frag_cover_user_photo:
                    Intent intent1 = new Intent(ArticleInfoActivity.this, UpinfoActivity.class);
                    //相关值传递
                    startActivity(intent1);
                    break;
                case R.id.frag_markup:
                    //关注up主逻辑
                    break;
            }
        }
    }
    
    private void addImageClickListner() {
        // 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，函数的功能是在图片点击的时候调用本地java接口并传递url过去  
        wv_articleinfo.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "    objs[i].onclick=function()  " +
                "    {  "
                + "        window.imggetter.openImage(this.src);  " +
                "    }  " +
                "}" +
                "})()");
    }

}
